package ph.com.gs3.chat.fragments.view;

import java.util.ArrayList;
import java.util.List;

import ph.com.gs3.chat.R;
import ph.com.gs3.chat.adapters.OnlineUserListItemViewAdapter;
import ph.com.gs3.chat.model.valueobject.business.UserStub;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class OnlineUsersViewFragment extends Fragment {

	public static final String TAG = OnlineUsersViewFragment.class.getSimpleName();

	private ListView lvOnlineUserList;
	private OnlineUserListItemViewAdapter adapter;
	private List<UserStub> users;

	private OnlineUsersViewActionListener listener;

	public OnlineUsersViewFragment() {
		users = new ArrayList<>();
	}

	public OnlineUsersViewFragment(List<UserStub> users) {
		this.users = users;
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		try {
			listener = (OnlineUsersViewActionListener) activity;
		} catch (ClassCastException e) {
			throw new IllegalStateException(activity.getClass().getSimpleName()
			        + " must implement " + OnlineUsersViewActionListener.class.getSimpleName());
		}

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_online_users, container, false);

		adapter = new OnlineUserListItemViewAdapter(getActivity(), users);

		lvOnlineUserList = (ListView) rootView.findViewById(R.id.OnlineUsers_lvUserListView);
		lvOnlineUserList.setAdapter(adapter);
		lvOnlineUserList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				listener.onOnlineUserClicked(users.get(position));
			}

		});

		return rootView;
	}

	public void setImageServer(String imageServer) {
		adapter.setImageServer(imageServer);
	}

	public void clearUsers() {
		users.clear();
		adapter.notifyDataSetChanged();
	}

	public void addUsers(List<UserStub> users) {
		this.users.addAll(users);
		this.adapter.notifyDataSetChanged();
	}

	public void addUser(UserStub user) {
		users.add(user);
		adapter.notifyDataSetChanged();
	}

	public void removeUser(String userId) {
		for (UserStub user : users) {
			if (user.getId().equals(userId)) {
				users.remove(user);
			}
		}
		adapter.notifyDataSetChanged();
	}

	public static interface OnlineUsersViewActionListener {
		public void onOnlineUserClicked(UserStub user);
	}

}
